package net.lainiao;

import com.google.common.collect.Lists;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.test.TestingServer;
import org.apache.curator.utils.CloseableUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;

/**
 * Created by Administrator on 2016/11/9.
 */
public class LeaderSelectorExample2 {
    private static final int QTY=10;
    private static final String PATH="/LeaderSelectorExample2/leader";

    public static void main( String[] args )throws Exception {
        List<CuratorFramework> clients= Lists.newArrayList();
        List<ExampleClient> exampleClients=Lists.newArrayList();
        TestingServer server=new TestingServer();
        try {
            for (int i = 0; i < QTY; i++) {
                CuratorFramework client= CuratorFrameworkFactory.newClient(server.getConnectString(),new ExponentialBackoffRetry(1000,3));
                clients.add(client);
                ExampleClient exampleClient=new ExampleClient(client,PATH,"Client #"+i);
                exampleClients.add(exampleClient);
                client.start();
                exampleClient.start();
            }
            System.out.println("Press Enter/return to quit");
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
            while (true){
                String line=bufferedReader.readLine();
                if(line.equals("exit")){
                    break;
                }
            }
        }catch (Exception e){
            System.out.println(e.fillInStackTrace());
        }
        finally {
            System.out.println("shutting down ....");

            for (ExampleClient exampleClient:exampleClients){
                CloseableUtils.closeQuietly(exampleClient);
            }

            for (CuratorFramework client:clients){
                CloseableUtils.closeQuietly(client);
            }

            CloseableUtils.closeQuietly(server);
        }
    }
}
